package com.sean.controller;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.xml.stream.events.EndDocument;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.xdevapi.JsonArray;

import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import freemarker.template.TemplateNotFoundException;


public class Test {

	public static void main(String[] args) {
		String dbName = "npm_bobahappy_co";
		String url = "jdbc:mysql://124.222.136.19:3306/"+dbName;  
        String user = "npm_bobahappy_co";  
        String password = "cyT5hrCEYb224YLY";  
        String pref = "eb_";  //表前缀
        String shortName = "company";  //表简写
		String tableName = "platform_company_info";

        JSONArray tables = new JSONArray();
        
        //配置表名
        JSONObject company = new JSONObject();
        company.put("tableName", "platform_company_info");
        
        //外键配置
        JSONArray foreignKeys = new JSONArray();
        JSONObject key = new JSONObject();
        key.put("selfKey", "parent_id");
        key.put("foreClass", "platform_company_info");
        key.put("foreKey", "id");
        key.put("foreName", "name");
        foreignKeys.add(key);
        company.put("foreignKey", foreignKeys);
        company.put("formWay", 0);//表单方式，0表示BuildForm 1表示弹窗
        
        
        
        tables.add(company);
        System.out.println(tables.toJSONString());
        
        //开始生成
        startGene(tables); 
        
        
        
       
//		System.out.println("开始解析"); 
//        try (Connection conn = DriverManager.getConnection(url, user, password)) {  
//            DatabaseMetaData metaData = conn.getMetaData();  
//            String tableComment = "";
//            alalyis(dbName, tableName, pref, conn, metaData, tableComment,shortName); 
//        } catch (SQLException e) {  
//            e.printStackTrace();  
//        }  
//		System.out.println("执行");
	}
	
	private static void startGene(JSONArray tables) {
		for (Object object : tables) {
			JSONObject table = (JSONObject) object;
			if(null != table.get("foreignKey")) {
				JSONArray forekeys = (JSONArray) table.get("foreignKey");
				for (Object keys : forekeys) {
					JSONObject key = (JSONObject) keys;
					//判断外键是否是自己
					if(table.get("tableName").toString().equalsIgnoreCase(key.getString("foreClass"))) {
						
					}
				}//end for
			}// end if
			
		}// end for
		
	}

	//解析数据库表
	private static void alalyis(String dbName, String tableName, String pref, Connection conn,
			DatabaseMetaData metaData, String tableComment,String shortName) throws SQLException {
		//获取表信息 
		try (Statement stmt = conn.createStatement();  
		     ResultSet rs = stmt.executeQuery(  
		         "SELECT TABLE_COMMENT FROM information_schema.TABLES " +  
		         "WHERE TABLE_SCHEMA = '"+dbName+"' AND TABLE_NAME = '"+pref + tableName + "'"  
		 )) {  
		    if (rs.next()) {  
		    	tableComment = rs.getString("TABLE_COMMENT");  
		        System.out.println("Table Comment: " + tableComment);  
		        System.out.println("-------------------");  
		    } else {  
		        System.out.println("No table comment found for " + pref +tableName);  
		    }  
		}  
		
		//获取表字段信息
		JSONArray columns = new JSONArray();
		try (ResultSet rs = metaData.getColumns(null, null, pref +tableName, null)) {  
		    while (rs.next()) {  
		        String columnName = rs.getString("COLUMN_NAME");  
		        String dataType = rs.getString("TYPE_NAME");  
		        int dataSize = rs.getInt("COLUMN_SIZE");  
		        boolean isNullable = rs.getBoolean("NULLABLE");  
		        String comment = rs.getString("REMARKS");  

		        if(columnName.equalsIgnoreCase("is_del")) {
		        	continue;
		        }
		        if(columnName.equalsIgnoreCase("created_time")) {
		        	continue;
		        }
		        if(columnName.equalsIgnoreCase("created_uid")) {
		        	continue;
		        }
		        if(columnName.equalsIgnoreCase("updated_time")) {
		        	continue;
		        }
		        if(columnName.equalsIgnoreCase("updated_uid")) {
		        	continue;
		        }
		        JSONObject column = new JSONObject();
		        column.put("columnName", columnName);
		        column.put("dataType", dataType);
		        column.put("comment", comment);
		        column.put("dataSize", dataSize);
		        column.put("isNull", isNullable);
		        columns.add(column);
		    }//end while
		    
		    for (Object object : columns) {
		    	JSONObject column = (JSONObject) object;
		    	if(column != null) {
		    		System.out.println(column.toJSONString());
		            System.out.println("-------------------");  
		    	}
			}
		    
		    
		    //开始生成代码
		    System.out.println("开始生成代码....");
		    String tableClass =  toCamelCase(tableName); 
		    
			Map<String, Object> root = new HashMap<>();  
			root.put("tableComment", tableComment);  
			root.put("tableClass", tableClass);  
			root.put("tableName", tableName);   
			root.put("columns", columns);     
			root.put("shortName", shortName);  

			Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);  
			cfg.setClassForTemplateLoading(Test.class, "/templates/"); 

			cfg.setDefaultEncoding("UTF-8");  
			cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);  
			cfg.setLogTemplateExceptions(false);  
			cfg.setWrapUncheckedExceptions(true); 
			
			String tempModelName = "model.ftl";
			geneCode(tableClass, root, cfg, tempModelName);
			
			String tempDaoName = "dao.ftl";
			geneCode(tableClass+"Dao", root, cfg, tempDaoName);
			
			String tempServiceName = "service.ftl";
			geneCode(tableClass+"Services", root, cfg, tempServiceName);
			
			String tempControllerName = "controller.ftl";
			geneCode(tableClass+"Controller", root, cfg, tempControllerName);
			
			String tempRouteName = "route.ftl";
			geneCode(shortName, root, cfg, tempRouteName);
			
			String tempApiName = "api.ftl";
			geneCodeJs(shortName, root, cfg, tempApiName);
			

			String tempIndexName = "front/index.ftl";
			geneCodeVue("index", root, cfg, tempIndexName);
			String tempFormName = "front/form.ftl";
			geneCodeVue("menusForm", root, cfg, tempFormName);
		    
		    //end 
		    System.out.println("结束生成代码....");
		} catch (Exception e) {
			System.out.println(e);
		}
	}

	/**
	 * 使用模板生成代码
	 * */
	private static void geneCode(String tableClass, Map<String, Object> root, Configuration cfg, String tempName)
			throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException,
			UnsupportedEncodingException, FileNotFoundException, TemplateException {
		Template temp = cfg.getTemplate(tempName);    
		Writer out = new OutputStreamWriter(new FileOutputStream("/Users/simple/Documents/projects/code/"+tableClass+".php"), "UTF-8");
		temp.process(root, out);
	}
	
	/**
	 * 使用模板生成代码
	 * */
	private static void geneCodeJs(String tableClass, Map<String, Object> root, Configuration cfg, String tempName)
			throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException,
			UnsupportedEncodingException, FileNotFoundException, TemplateException {
		Template temp = cfg.getTemplate(tempName);    
		Writer out = new OutputStreamWriter(new FileOutputStream("/Users/simple/Documents/projects/code/"+tableClass+".js"), "UTF-8");
		temp.process(root, out);
	}
	
	/**
	 * 使用模板生成代码
	 * */
	private static void geneCodeVue(String tableClass, Map<String, Object> root, Configuration cfg, String tempName)
			throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException,
			UnsupportedEncodingException, FileNotFoundException, TemplateException {
		Template temp = cfg.getTemplate(tempName);    
		Writer out = new OutputStreamWriter(new FileOutputStream("/Users/simple/Documents/projects/code/"+tableClass+".vue"), "UTF-8");
		temp.process(root, out);
	}
	

	/**
	 * 使用模板生成代码
	 * */
	public static String toCamelCase(String s) {  
	    if (s == null) {  
	        return null;  
	    }  
	      
	    s = s.toLowerCase();  
	      
	    StringBuilder sb = new StringBuilder();  
	    boolean upperCase = true;  
	    for (int i = 0; i < s.length(); i++) {  
	        char c = s.charAt(i);  
	          
	        if (c == '_') {  
	            upperCase = true;  
	        } else if (upperCase) {  
	            sb.append(Character.toUpperCase(c));  
	            upperCase = false;  
	        } else {  
	            sb.append(c);  
	        }  
	    }  
	      
	    return sb.toString();  
	}

}
